package main

import (
	"context"
	common "git.mashibing.com/msb_47094/shopping-comm"
	"gouser/proto"
	"log"
	"strconv"

	consul "github.com/asim/go-micro/plugins/registry/consul/v4"
	"go-micro.dev/v4/registry"
	"go-micro.dev/v4/web"

	"github.com/gin-gonic/gin"
	"go-micro.dev/v4"
)

// 获取远程服务的客户端
func getClient() proto.LoginService {
	//注册到consul
	consulReg := consul.NewRegistry(func(options *registry.Options) {
		options.Addrs = []string{common.ConsulIp + ":8500"}
	})
	rpcServer := micro.NewService(
		micro.Registry(consulReg),
	)
	return proto.NewLoginService("shop-user", rpcServer.Client())
}
func main() {
	router := gin.Default()

	router.Handle("GET", "toLogin", func(context *gin.Context) {
		context.String(200, "to Loging ....")
	})

	router.GET("/login", func(c *gin.Context) {
		//获取远程服务的客户端
		client := getClient()
		//获取页面参数
		clientId, _ := strconv.Atoi(c.Request.FormValue("clientId"))
		phone := c.Request.FormValue("phone")
		systemId, _ := strconv.Atoi(c.Request.FormValue("systemId"))
		verificationCode := c.Request.FormValue("verificationCode")
		//拼接请求信息
		req := &proto.LoginRequest{
			ClientId:         int32(clientId),
			Phone:            phone,
			SystemId:         int32(systemId),
			VerificationCode: verificationCode,
		}
		//远程调用服务
		resp, err := client.Login(context.TODO(), req)
		//根据响应做输出
		if err != nil {
			log.Println(err.Error())
			//c.String(http.StatusBadRequest, "search failed !")
			common.RespFail(c.Writer, resp, "登录失败")
			return
		}
		common.RespOK(c.Writer, resp, "登录成功")
	})

	service := web.NewService(
		web.Address(":6666"),
		web.Handler(router),
	)
	service.Run()
	// router.Run(":6666")
}
